package com.example.androidlearning.sy10.sy2sqlite;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.example.androidlearning.R;

import java.util.List;
import java.util.Map;

public class Sy1002_ContentAdapter extends BaseAdapter implements View.OnClickListener {
    private static final String TAG = "Sy1002_ContentAdapter";
    private List<Map<String, String>> mContentList;
    private LayoutInflater mInflater;   //LayoutInflater它主要是用于加载布局
    private Callback mCallback;     //回调

    public interface Callback {
        public void click(View view);
    }

    public Sy1002_ContentAdapter(Context context, List<Map<String, String>> contentList,
                                 Callback callback) {
        mContentList = contentList;
        mInflater = LayoutInflater.from(context);
        mCallback = callback;
    }

    @Override
    public int getCount() {   //获取列表项项数
        Log.i(TAG, "getCount");
        return mContentList.size();
    }

    @Override
    public Object getItem(int position) {  //根据列表项位置索引获取列表项绑定的数据
        Log.i(TAG, "getItem");
        return mContentList.get(position);
    }

    @Override
    public long getItemId(int position) {
        Log.i(TAG, "getItemId");
        return position;
    }

    @SuppressLint("InflateParams")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {  //把数据和列表项的控件进行绑定
        Log.i(TAG, "getView");
        ViewHolder holder = null;
        if (convertView == null) {  //如果列表项没有初始化就进行初始化
            convertView = mInflater.inflate(R.layout.custom_item_sy1002, null);
            holder = new ViewHolder();
            holder.tv_account = convertView.findViewById(R.id.tv_account);
            holder.tv_name = convertView.findViewById(R.id.tv_name);
            holder.btn_del = convertView.findViewById(R.id.deleteBtn);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.tv_account.setText(mContentList.get(position).get("account"));
        holder.tv_name.setText(mContentList.get(position).get("name"));
        holder.btn_del.setOnClickListener(this);
        holder.btn_del.setTag(position);
        return convertView; //返回一个列表项
    }

    public class ViewHolder {  //列表项所有控件组成一个类
        public TextView tv_account;
        public TextView tv_name;
        public Button btn_del;
    }

    //响应按钮点击事件,调用子定义接口，并传入View
    @Override
    public void onClick(View v) {
        mCallback.click(v);
    }
}

